import {
  addExamTestPaperModule,
  delExamTestPaperModule,
  getExamTestPaperModule,
  listExamTestPaperModule,
  updateExamTestPaperModule
} from "@/api/train/base/ExamTestPaperModule";
import mixins from "@/views/train/mixins";
import {QUESTION_TYPE, TEST_PAPER_TYPE, USER_TYPE} from "@/views/train/Enums";
import ExamQuestionBank from './ExamQuestionBank'

export default {
  name: "ExamTestPaperModule",
  mixins: [mixins],
  components: {
    ExamQuestionBank
  },
  computed: {
    defaultSelectedIds() {
      return this.requiredExamList.map(e => e.questionId)
    }
  },
  data() {
    return {
      postSubjectPointTree: [],
      postSubjectPointTreeAll: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedExamTestPaperExtractRule: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷模板表格数据
      ExamTestPaperModuleList: [],
      // 试卷试题抽取规则表格数据
      examTestPaperExtractRuleList: [],
      // 固定题目数据
      requiredExamList: [],
      // 选中的固定题目的数据
      checkedRequiredExamList: [],
      // 选取题目的表格是否可见
      requiredExamVisible: false,
      // 选取题目的表格的查询参数
      requiredExamParams: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        userType: null,
        type: null,
        passGrade: undefined,
        totalGrade: undefined,
        deptId: null,
        postId: null,
        postLevelCode: null,
        isDel: null,
        delBy: null,
        delTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "试卷名称不能为空", trigger: "blur"}
        ],
        userType: [
          {required: true, message: "使用类型不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "试卷类型不能为空", trigger: "blur"}
        ],
        passGrade: [
          {required: true, message: "及格分数不能为空", trigger: "blur"}
        ],
        totalGrade: [
          {required: true, message: "总分数不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "部门不能为空", trigger: "blur"}
        ],
        postId: [
          {required: true, message: "岗位不能为空", trigger: "blur"}
        ],
        postLevelCode: [
          {required: true, message: "岗位级别不能为空", trigger: "blur"}
        ],
      },
      options: {
        deptList: [],
        postList: [],
        TEST_PAPER_TYPE,
        QUESTION_TYPE,
        USER_TYPE,
        rulePostLevel: [],
      },
    };
  },

  watch: {
    'form.postId': {
      handler(value) {
        if (value) {
          let index = this.postSubjectPointTreeAll.findIndex(e => e.id === value)
          this.postSubjectPointTree = this.postSubjectPointTreeAll[index].children
        } else {
          this.postSubjectPointTree = []
        }
        this.$refs.postSubjectPointCascader && this.$refs.postSubjectPointCascader.validate()
      },
      // immediately: true
    },
    // 'form.postLevelCode': {
    //   handler(value) {
    //     if (value) {
    //       let rulePostLevel = []
    //       this.dict.type.post_level.forEach(e => {
    //         if (Number(e.value) <= Number(value)) {
    //           rulePostLevel.push(e)
    //         }
    //       })
    //       this.options.rulePostLevel = rulePostLevel
    //       this.$nextTick(() => {
    //         Object.keys(this.$refs).forEach(key => {
    //           if (~key.indexOf('postLevelCodeSelector')) {
    //             this.$refs[key].validate()
    //           }
    //         })
    //       })
    //     } else {
    //       this.options.rulePostLevel = []
    //       this.examTestPaperExtractRuleList.forEach(e => {
    //         e.postLevelCode = ''
    //       })
    //     }
    //   }
    // }
  },
  methods: {
    noop(event) {
      const target = event.target;
      if (target.matches('.el-input-number')) { // 假设 .el-input-number 是 el-input-number 的类名
        event.stopPropagation();
        event.stopImmediatePropagation();
      }
    },
    handleKnowledgePointsChange(row) {
      if (row.knowledgePointId.length !== 2) {
        this.$message.warning('请选择知识点层级!')
        row.knowledgePointId = []
      }
    },
    /** 查询试卷模板列表 */
    getList() {
      this.loading = true;
      listExamTestPaperModule(this.doSort(this.queryParams,'createTime' )).then(response => {
        this.ExamTestPaperModuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        userType: null,
        type: null,
        passGrade: 60,
        totalGrade: 100,
        deptId: null,
        postId: null,
        postLevelCode: null,
        remark: null
      };
      this.examTestPaperExtractRuleList = [];
      this.requiredExamList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExamTestPaperModule(id).then(response => {
        this.form = response.data;
        // 数据赋值
        this.examTestPaperExtractRuleList = response.data.examTestPaperExtractRuleList;
        this.examTestPaperExtractRuleList.forEach(e => {
          e.knowledgePointId = [e.subjectId, e.knowledgePointId]
        })
        this.requiredExamList = response.data.examTestPaperRequired
        this.open = true;
        this.title = "修改试卷模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {

        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))
          let examTestPaperExtractRuleList = JSON.parse(JSON.stringify(this.examTestPaperExtractRuleList))
          let requiredExamList = JSON.parse(JSON.stringify(this.requiredExamList))
          let errList = []
          examTestPaperExtractRuleList.forEach((e, i) => {
            if (!(
              e.questionType &&
              e.grade &&
              e.number &&
              e.syllabusCode &&
              e.postLevelCode &&
              Array.isArray(e.knowledgePointId) && e.knowledgePointId.length === 2
            )) {
              errList.push(`规则信息第${i + 1}行内容不全`)
            }
          })
          requiredExamList.forEach((e, i) => {
            if (!(e.questionId && e.grade)) {
              errList.push(`固定题目第${i + 1}行内容不全`)
            }
          })
          if (errList.length) {
            this.$message.warning(errList.toString())
            return
          }
          examTestPaperExtractRuleList.forEach(e => {
            let [subjectId, knowledgePointId] = e.knowledgePointId
            e.subjectId = subjectId
            e.knowledgePointId = knowledgePointId
          })
          form.examTestPaperExtractRuleList = examTestPaperExtractRuleList;
          form.examTestPaperRequired = requiredExamList;
          if (form.id != null) {
            updateExamTestPaperModule(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamTestPaperModule(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认删除？').then(function () {
        return delExamTestPaperModule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 试规则序号 */
    rowIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 试卷试题抽取规则添加按钮操作 */
    handleAddExamTestPaperExtractRule() {
      let obj = {};
      obj.questionType = "";
      obj.grade = "";
      obj.number = "";
      obj.syllabusCode = "";
      obj.subjectId = "";
      obj.knowledgePointId = [];
      obj.remark = "";
      this.examTestPaperExtractRuleList.push(obj);
    },
    /** 试卷试题抽取规则删除按钮操作 */
    handleDeleteExamTestPaperExtractRule() {
      if (this.checkedExamTestPaperExtractRule.length == 0) {
        this.$modal.msgError("请先选择要删除的试卷试题抽取规则数据");
      } else {
        const examTestPaperExtractRuleList = this.examTestPaperExtractRuleList;
        const checkedExamTestPaperExtractRule = this.checkedExamTestPaperExtractRule;
        this.examTestPaperExtractRuleList = examTestPaperExtractRuleList.filter(function (item) {
          return checkedExamTestPaperExtractRule.indexOf(item.index) == -1
        });
      }
    },
    /** 试卷试题必选题添加按钮操作 */
    handleAddExamTestRequired() {
      let {postId, deptId, postLevelCode} = this.form
      if (postId && deptId && postLevelCode) {
        this.requiredExamParams = {
          postId: this.form.postId,
          deptId: this.form.deptId,
          postLevelCode: this.postLevelCode,
        }
        this.requiredExamVisible = true
        this.$nextTick(_ => {
          this.$refs.requiredExamTable.init()
        })
      } else {
        this.$message.warning('请先完善上方表单内容!')
      }
    },
    /** 试卷试题抽取规则删除按钮操作 */
    handleDeleteExamTestRequired() {
      if (this.checkedRequiredExamList.length == 0) {
        this.$modal.msgError("请先选择要删除的试题");
      } else {
        const requiredExamList = this.requiredExamList;
        const checkedRequiredExamList = this.checkedRequiredExamList;
        this.requiredExamList = requiredExamList.filter(function (item) {
          return checkedRequiredExamList.indexOf(item.index) == -1
        });
      }
    },
    /** 试卷试题抽取规则内确认按钮操作 */
    handleRequiredExamConfirm(selectedData) {
      selectedData.forEach(e => {
        // 将原本的分数给设置上
        this.requiredExamList.forEach(e1 => {
          if (e1.questionId === e.questionId) {
            e.grade = e1.grade
          }
        })
      })
      this.requiredExamList = selectedData
      this.requiredExamVisible = false
    },
    /** 试卷试题抽取规则内取消按钮操作 */
    handleRequiredExamCancel() {
      this.requiredExamVisible = false
    },
    /** 试卷试题抽取规则复选框选中数据 */
    handleRequiredExamSelectionChange(selection) {
      this.checkedRequiredExamList = selection.map(item => item.index)
    },
    /** 复选框选中数据 */
    handleExamTestPaperExtractRuleSelectionChange(selection) {
      this.checkedExamTestPaperExtractRule = selection.map(item => item.index)
    },
    // 固定题目行点击事件
    handleRequiredExamRowClick(row) {
      this.$refs.examRequiredExam.toggleRowSelection(row)
    },
    // 抽取规则行点击事件
    handleExtractRuleRowClick(row) {
      this.$refs.examTestPaperExtractRule.toggleRowSelection(row)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('train/ExamTestPaperModule/export', {
        ...this.queryParams
      }, `ExamTestPaperModule_${new Date().getTime()}.xlsx`)
    },
    async init() {
      this.getList()
      this.postSubjectPointTreeAll = await this.getPostSubjectPointTree()
      this.options.deptList = (await this.getDepts()).list
      this.options.postList = (await this.getPosts()).list
    },
  },
  created() {
    this.init();
  },
};
